package com.zjun.demo.ruleview

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.zjun.demo.ruleview.TimeRuleView.TimePart
import java.lang.Thread.sleep
import java.util.Random
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity() {

    private lateinit var trvTime: TimeRuleView

    private lateinit var timeRuleView: MyTimeRuleView

    private lateinit var tvTime: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        trvTime = findViewById(R.id.trv_time)
        timeRuleView = findViewById(R.id.timeRuleView1)
        tvTime = findViewById(R.id.tv_time)
        trvTime.setOnTimeChangedListener { newTimeValue ->
            tvTime.text = TimeRuleView.formatTimeHHmmss(
                newTimeValue
            )
        }
        // 模拟时间段数据
        val list: MutableList<TimePart> = ArrayList()
        for (i in 0..9) {
            val part = TimePart()
            part.startTime = i * 1000
            part.endTime = part.startTime + Random().nextInt(1000)
            list.add(part)
        }
        trvTime.setTimePartList(list)
        timeRuleView.setTimePartList(list)
    }

    fun expand(view: View) {
        trvTime.mfoewf(1.1f)
    }

    fun reduce(view: View) {
        trvTime.mfoewf(0.9f)
    }

    fun start(view: View) {
        thread {
            sleep(5000)
            runOnUiThread {
//                val intent =  Intent(this, MainActivity::class.java)
//                intent.addCategory(Intent.CATEGORY_LAUNCHER)
//                intent.setAction(Intent.ACTION_MAIN)
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                startActivity(intent)



                setTopApp(this)
            }
        }
    }


    fun setTopApp(context: Context) {
        if (true) {
            val activityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
            //获得当前运行的task(任务)
            val taskInfoList = activityManager.getRunningTasks(100)
            for (taskInfo in taskInfoList) {
                Log.e("MainActivity", "进程Task：" + taskInfo.topActivity!!.packageName)
                //找到本应用的 task，并将它切换到前台
                if (taskInfo.topActivity!!.packageName == context.packageName) {
                    val ss = getTaskId()
                    val ss1 = taskInfo.id
                    activityManager.moveTaskToFront(taskInfo.id, 0)
                    break
                }
            }
        }
    }


}